import time

from PyQt6 import QtWidgets, uic
import sys, os, socket, threading
from socketThread import My_socket
from My_signal import Communicator



class My_ui_thread(QtWidgets.QWidget):

    def __init__(self, filename, port):
        super().__init__()
        self.ui_widget = uic.loadUi(filename)
        self.hostname = socket.gethostname()
        self.ip = socket.gethostbyname(self.hostname)
        self.port = port or 5000
        self.ui_widget.comboBox.addItem(self.ip)
        self.ui_widget.spinBox.setValue(self.port)
        self.socket_instance = My_socket(self.ip, self.port)
        self.communicator = Communicator()
        # 绑定事件与槽
        # self.ui_widget.pushButton_start.clicked.connect(self.btn_start)
        self.ui_widget.pushButton_start.clicked.connect(self.btn_start)
        self.ui_widget.pushButton_stop.clicked.connect(self.btn_stop)
        self.ui_widget.pushButton_send.clicked.connect(self.btn_send)
        self.ui_widget.pushButton_clear.clicked.connect(self.btn_clear)
        print("ip:", self.ip)

    def btn_start(self):
        print("开启服务")
        t = threading.Thread(target=self.socket_instance.start_tcp)
        t.start()

    def btn_stop(self):
        print("停止服务")
        self.socket_instance.close_tcp()

    def btn_send(self):
        print("发送消息")
        msg = self.ui_widget.lineEdit.text()
        # 发送消息
        self.communicator.custom_signal.emit(msg)

    def btn_clear(self):
        print("清空消息")

    def closeEvent(self, event):
        print("GUANBI")
        self.socket_instance.close_tcp()
        event.accept()



def main():
    global ui
    filename = os.getcwd()
    filename += "\\UI\\tcp_server.ui"
    try:
        app = QtWidgets.QApplication(sys.argv)
        ui = My_ui_thread(filename, 5000)
        ui.ui_widget.show()
        sys.exit(app.exec())
    except Exception as e:
        print("error:", e)
        ui.socket_instance.close_tcp()


if __name__ == "__main__":
    main()
